package com.sskj.level.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.widget.RxRadioGroup;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.level.bean.CoinUpdateBean;
import com.sskj.level.bean.TradeInfoBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.BuyAndSellFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.MoreLessBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppOuterCheckUtil;
import com.sskj.lib.util.BottomSheetUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;

import static com.sskj.level.http.HttpConfig.DEFAULT_COIN;

@Route(path = RConfig.LEVEL_FRAGMENT_BUY_AND_SELL)//合约交易买卖
public class BuyAndSellFragment extends BaseFragment<BuyAndSellFragmentPresenter> {
    @BindView(R2.id.rbBuy)
    RadioButton rbBuy;
    @BindView(R2.id.rbSell)
    RadioButton rbSell;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.spinner)
    TextView spinner;
    @BindView(R2.id.llPriceMode)
    LinearLayout llPriceMode;
    @BindView(R2.id.etPrice)
    EditText etPrice;
    @BindView(R2.id.tvDecrease)
    TextView tvDecrease;
    @BindView(R2.id.cuttingLine)
    TextView cuttingLine;
    @BindView(R2.id.tvIncrease)
    TextView tvIncrease;
    @BindView(R2.id.llAddAndDe)
    LinearLayout llAddAndDe;
    @BindView(R2.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R2.id.llHidePrice)
    LinearLayout llHidePrice;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.tvCoinType)
    TextView tvCoinType;
    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.rgLevel)
    RadioGroup rgLevel;
    @BindView(R2.id.tvTradeMoney)
    TextView tvTradeMoney;
    @BindView(R2.id.top)
    LinearLayout top;
    @BindView(R2.id.sellRecyclerView)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.buyRecyclerView)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.loadingLayout)
    FrameLayout loadingLayout;
    @BindView(R2.id.tvStopWinDot)
    TextView tvStopWinDot;
    @BindView(R2.id.etStopWinDot)
    EditText etStopWinDot;
    @BindView(R2.id.tvStopLoseDot)
    TextView tvStopLoseDot;
    @BindView(R2.id.etStopLoseDot)
    EditText etStopLoseDot;
    @BindView(R2.id.btTrade)
    Button btTrade;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.coin_price)
    TextView coinPrice;
    @BindView(R2.id.coin_money)
    TextView coinMoney;
    @BindView(R2.id.tvNumDecrease)
    TextView tvNumDecrease;
    @BindView(R2.id.tvNumIncrease)
    TextView tvNumIncrease;
    @BindView(R2.id.left_coin_money)
    TextView leftCoinMoney;
    @BindView(R2.id.inputLayoutWin)
    TextInputLayout inputLayoutWin;
    @BindView(R2.id.inputLayoutLoss)
    TextInputLayout inputLayoutLoss;
    @BindView(R2.id.tvLevelTitle)
    TextView tvLevelTitle;
    @BindView(R2.id.dymic_qy)
    TextView dymicQy;
    @BindView(R2.id.level_fxl)
    TextView levelFxl;
    @Inject
    UserViewModel userViewModel;
    private SlimAdapter<WSFiveBean.FiveBean> sellSlimAdapter;
    private SlimAdapter<WSFiveBean.FiveBean> buySlimAdapter;
    String code = DEFAULT_COIN;//币种类型code
    String type = "BTC";//币种类型
    private BottomSheetDialog priceModeSheet;
    private boolean isBuy = true;
    private boolean isMarketPrice = true;  // 市价限价  （默认市价）
    private String marketPrice = "5000";//市价
    private String currentPrice = "5000";//限价
    private String usdtMoney = "1000";//可用USDT
    private String rate = "0.0001";//加减的点
    private String rateNum = "1";// 数量加减的点
    private int priceKeepDot = 4;//价格小数点位
    private int numUSTDKeepDot = 4;//数量小数点位
    private int numCoinKeepDot = 4;//数量小数点位
    private String maxTradeCoin = "10";//最大可交易币种数量
    private String minTradeCoin = "10";//最小可交易币种数量
    private String fee = "0.15";//手续费
    private Double level = 20d;//杠杆
    private String minFloatPrice = "0";//最小浮动价
    private String dotDistance = "0";//点差
    private String levels;//杠杆
    private UserData userData;
    private String minLoss = "0";//最小止损
    private String maxLoss = "0";//最大止损
    private String maxWin = "0";//最大止赢
    private String minWin = "0";//最小止赢
    private String distancePrice = "0";
    private int dotLoss;
    private int dotWin;
    private String winMinPrice;
    private String winMaxPrice;
    private String lossMinPrice;
    private String lossMaxPrice;
    private String stopLossPrice = "--";
    private String stopWinPrice = "--";
    private String orderPrice;
    private Disposable subscribe;
    private String cnyPrice;


    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_buy_sell;
    }

    @Override
    public BuyAndSellFragmentPresenter getPresenter() {
        return new BuyAndSellFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        initFive();
        initClick();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                usdtMoney = userData.getUsableFund();
            } else {
                userData = null;
                usdtMoney = "0";
                btTrade.setText(App.INSTANCE.getString(R.string.levelBuyAndSellFragment16));
            }
            updateUI();
        });
    }

    @Override
    public void initData() {
        loadingLayout.setVisibility(View.GONE);
        resetFiveUI();
        mPresenter.getPankou(code);
        mPresenter.getCoinInfo(code);
        userViewModel.update();
        startTimer();

    }

    /**
     * 更换币种--左侧栏选择币种
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        isBuy = coinType.isBuy();
        isMarketPrice = true;
        code = coinType.getCode();
        type = coinType.getCode().split("/")[0].toUpperCase();
        resetFiveUI();
        mPresenter.getPankou(code);
        refresh();
    }

    /**
     * 刷新页面
     */
    @Subscribe(code = RxBusCode.LEVEL_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        mPresenter.getCoinInfo(code);
        userViewModel.update();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(StockCoinBean.StockProductVOBean stock) {
        if (stock.getCode().equals(code) && getActivity() != null) {
            marketPrice = stock.getPrice();
            tvPrice.setText(marketPrice);
            coinPrice.setText(marketPrice);
            coinMoney.setText("≈" + stock.getCnyPrice() + " CNY");
            leftCoinMoney.setText("≈" + stock.getCnyPrice() + " CNY");
            changeShowData();
        }
    }

    public void updateCoinData(CoinUpdateBean coinUpdateBean) {
        currentPrice = marketPrice = coinUpdateBean.getPrice();
        type = code.split("/")[0].toUpperCase();
        fee = new BigDecimal(coinUpdateBean.getShouPer()).multiply(new BigDecimal("0.01")).toPlainString();
        minFloatPrice = coinUpdateBean.getSlidingScalePrice();
        dotDistance = coinUpdateBean.getSpread();
        //   最小浮动价* 点差(买入价格 = 当前价格 + 最小浮动价* 点差  卖出价格 =当前价格 -最小浮动价* 点差 )
        distancePrice = new BigDecimal(minFloatPrice).multiply(new BigDecimal(dotDistance)).toPlainString();
        minLoss = coinUpdateBean.getMinStopLoss();
        maxLoss = coinUpdateBean.getStopLoss();
        minWin = coinUpdateBean.getMinStopProfit();
        maxWin = coinUpdateBean.getStopProfit();
        minTradeCoin = coinUpdateBean.getMinDealNum();
        levels = coinUpdateBean.getLevels();
        level = Double.valueOf(coinUpdateBean.getLevels().split(",")[0]);
        updateLevelButton();
        updateUI();

    }

    /**
     * 动态更新杠杆按钮
     */
    private void updateLevelButton() {
        rgLevel.setVisibility(View.INVISIBLE);
        tvLevelTitle.setVisibility(View.INVISIBLE);
        rgLevel.removeAllViews();
        if (levels.split(",").length >= 1) {
            Flowable.fromArray(levels.split(","))
                    .filter(s -> !TextUtils.isEmpty(s))
                    .subscribe(s -> {
                        RadioButton radioButton = new RadioButton(getActivity());
                        radioButton.setBackgroundResource(R.drawable.level_percent);    // 设置RadioButton的背景图片
                        radioButton.setButtonDrawable(null);            // 设置按钮的样式
                        radioButton.setText(s);
                        radioButton.setPadding(5, 0, 5, 0);
                        radioButton.setGravity(Gravity.CENTER);
                        radioButton.setWidth(0);
                        radioButton.setTextColor(getResources().getColorStateList(R.color.level_selector_text_white));
                        radioButton.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
                        rgLevel.addView(radioButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) radioButton.getLayoutParams();
                        layoutParams.weight = 1;
                        if (!s.equals(levels.split(",")[0])) {
                            layoutParams.setMargins(5, 0, 0, 0);
                        }
                        radioButton.setLayoutParams(layoutParams);
                    });
            rgLevel.setVisibility(View.VISIBLE);
            tvLevelTitle.setVisibility(View.VISIBLE);
            rgLevel.check(rgLevel.getChildAt(0).getId());
        } else if (levels.split(",").length == 1) {
            level = Double.valueOf(levels.split(",")[0]);
        }
    }

    private void initFive() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        sellSlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().indexOf(data) + 1 + "")
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_FF3F3E))
                        .backgroundColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_66FF3F3E))
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : NumberUtil.keepMax(data.getPrice(), code.toUpperCase().contains("USDT") ? 4 : 8))
                        .text(R.id.tvNum, data.getTotalSize());
            }
        }).attachTo(sellRecyclerView).updateData(new ArrayList());
        buySlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : NumberUtil.keepMax(data.getPrice(), code.toUpperCase().contains("USDT") ? 4 : 8))
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_05C089))
                        .backgroundColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_6605C089))
                        .text(R.id.tvNum, data.getTotalSize());
            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(sellRecyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (isBuy && !isMarketPrice && position >= 0 && sellSlimAdapter.getData().size() > position && isBuy && !TextUtils.isEmpty(sellSlimAdapter.getDataItem(position).getPrice())) {
                        currentPrice = sellSlimAdapter.getDataItem(position).getPrice();
                        etPrice.setText(currentPrice);
                    } else {
//                        ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment24));
                    }
                });
        ItemClickSupport.addTo(buyRecyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (!isBuy && !isMarketPrice && position >= 0 && buySlimAdapter.getData().size() > position && !isBuy && !TextUtils.isEmpty(buySlimAdapter.getDataItem(position).getPrice())) {
                        currentPrice = buySlimAdapter.getDataItem(position).getPrice();
                        etPrice.setText(currentPrice);
                    } else {
//                        ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment24));

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateFive(WSFiveBean wsFiveBean) {
        if (wsFiveBean.getCode().equals(code)) {
            Collections.sort(wsFiveBean.getAsks(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            Collections.sort(wsFiveBean.getBids(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            if (wsFiveBean.getAsks().size() > 7) {
                int startIndex = wsFiveBean.getAsks().size() - 7;
                sellSlimAdapter.updateData(wsFiveBean.getAsks().subList(startIndex, wsFiveBean.getAsks().size()));
            } else {
                sellSlimAdapter.updateData(wsFiveBean.getAsks());
            }
            if (wsFiveBean.getBids().size() > 7) {
                buySlimAdapter.updateData(wsFiveBean.getBids().subList(0, 7));
            } else {
                buySlimAdapter.updateData(wsFiveBean.getBids());

            }
        }
    }

    /**
     * 设置买五卖五UI --
     */
    private void resetFiveUI() {
        WSFiveBean wsFiveBean = new WSFiveBean();
        wsFiveBean.setCode(code);
        ArrayList<WSFiveBean.FiveBean> asks = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> bids = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            asks.add(new WSFiveBean.FiveBean());
            bids.add(new WSFiveBean.FiveBean());
        }
        wsFiveBean.setAsks(asks);
        wsFiveBean.setBids(bids);
        updateFive(wsFiveBean);
    }

    private void initClick() {
        RxRadioGroup.checkedChanges(radioGroup)
                .subscribe(clickId -> {
                    if (!isBuy && clickId == rbBuy.getId()) {//购买
                        isBuy = true;
//                        isMarketPrice = true;
                        updateUI();
                    } else if (isBuy && clickId == rbSell.getId()) {//出售
                        isBuy = false;
//                        isMarketPrice = true;
                        updateUI();
                    }
                });
        ClickUtil.click(llPriceMode, () -> {
            if (priceModeSheet == null) {
                priceModeSheet = BottomSheetUtil.getBottomSheet(getActivity(), App.INSTANCE.getString(R.string.levelBuyAndSellFragment26), (recyclerView, position, v) -> {
                    priceModeSheet.dismiss();
                    if (position == 0 && !isMarketPrice) {
                        isMarketPrice = true;
                        updateUI();
                    } else if (position == 1 && isMarketPrice) {
                        isMarketPrice = false;
                        updateUI();
                    }
                }, App.INSTANCE.getString(R.string.levelBuyAndSellFragment27), App.INSTANCE.getString(R.string.levelBuyAndSellFragment28));
            }
            priceModeSheet.show();
        });
        ClickUtil.click(100, tvDecrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String decrease = "-" + rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(decrease));
            if (priceDecimal.doubleValue() <= 0) {
                etPrice.setText("0");
            } else {
                etPrice.setText(NumberUtil.keep(priceDecimal.toString(), priceKeepDot));
            }
        });
        ClickUtil.click(100, tvIncrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String increase = rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(increase));
            etPrice.setText(NumberUtil.keep(priceDecimal.toString(), priceKeepDot));
        });
        ClickUtil.click(tvNumDecrease, () -> {  // 减
            if (TextUtils.isEmpty(etNum.getText())) {
                etNum.setText(minTradeCoin);
                return;
            }
            String decrease = "-" + rateNum;
            BigDecimal priceDecimal = new BigDecimal(etNum.getText().toString()).add(new BigDecimal(decrease));
            if (priceDecimal.doubleValue() <= 0) {
                etNum.setText("0");
            } else {
                etNum.setText(NumberUtil.keep(priceDecimal.toString(), numCoinKeepDot));
            }
        });
        ClickUtil.click(tvNumIncrease, () -> {  // 加
            if (TextUtils.isEmpty(etNum.getText())) {
                etNum.setText(minTradeCoin);
                return;
            }
            String increase = rateNum;
            BigDecimal priceDecimal = new BigDecimal(etNum.getText().toString()).add(new BigDecimal(increase));
            etNum.setText(NumberUtil.keep(priceDecimal.toString(), numCoinKeepDot));
        });
        rgLevel.setOnCheckedChangeListener((group, checkedId) -> {
            level = Double.valueOf(levels.split(",")[group.indexOfChild(group.findViewById(checkedId))]);
            updateUI();
        });

        RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable().toString())) {
                        currentPrice = "0";
                    } else {
                        currentPrice = value.editable().toString();
                    }
                    calculateMaxTrade();
                    changeShowData();
                }, e -> System.out.println(e));
        RxTextView.afterTextChangeEvents(etNum)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable()) || Double.valueOf(value.editable().toString()) == 0 ||
                            TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                    } else {
                        if (Double.valueOf(value.editable().toString()) > Double.valueOf(maxTradeCoin)) {
                            etNum.setText(maxTradeCoin);
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment36));
                        }
                    }
                    changeShowData();
                });
        RxTextView.afterTextChangeEvents(etStopLoseDot)
                .subscribe(value -> {
                    String input = value.editable().toString();
                    stopLossPrice = "--";
                    if (TextUtils.isEmpty(input)) {
                        tvStopLoseDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment41), etStopLoseDot.getText().toString()));
                        return;
                    }
                    stopLossPrice = NumberUtil.keepMax(etStopLoseDot.getText().toString().trim(), numUSTDKeepDot);
//                    String orderPrice;
//                    if (isBuy) {
//                        orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
//                        stopLossPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//                    } else {
//                        orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
//                        stopLossPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//                    }
//                    stopLossPrice = NumberUtil.keepMax(stopLossPrice, numUSTDKeepDot);
//
//                    tvStopLoseDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment41), stopLossPrice));
                });
        RxTextView.afterTextChangeEvents(etStopWinDot)
                .subscribe(value -> {
                    String input = value.editable().toString();
                    stopWinPrice = "--";
                    if (TextUtils.isEmpty(input)) {
                        tvStopWinDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment46), etStopWinDot.getText().toString()));
                        return;
                    }
                    stopWinPrice = NumberUtil.keepMax(etStopWinDot.getText().toString().trim(), numUSTDKeepDot);
                    //计算止赢止损价格
//                    String orderPrice;
//                    if (isBuy) {
//                        orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
//                        stopWinPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//                    } else {
//                        orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
//                        stopWinPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//                    }
//                    stopWinPrice = NumberUtil.keepMax(stopWinPrice, numUSTDKeepDot);
//
//                    tvStopWinDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment46), stopWinPrice));
                });
    }

    /**
     * 更新界面根据
     * 买入卖出，市价限价，币种，可用金额 变化 初始化界面
     */
    private void updateUI() {
        calculateMaxTrade();
        radioGroup.check(isBuy ? R.id.rbBuy : R.id.rbSell);
        spinner.setText(isMarketPrice ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment27) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment28));
        rlEditPrice.setVisibility(isMarketPrice ? View.GONE : View.VISIBLE);
        llHidePrice.setVisibility(isMarketPrice ? View.VISIBLE : View.GONE);
        etPrice.setText(marketPrice);
        tvPrice.setText(marketPrice);
        etNum.setText("");
        etStopLoseDot.setText("");
        etStopWinDot.setText("");
        tvMoney.setText(usdtMoney);
//        tvCoinType.setText((isBuy && isMarketPrice) ? "USDT" : type);
//        etNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits((isBuy && isMarketPrice) ? numUSTDKeepDot : numCoinKeepDot)});
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(priceKeepDot)});
        etNum.setHint("最少" + minTradeCoin + ((isBuy && isMarketPrice) ? "USDT" : type));
//        etStopLoseDot.setHint(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment53), minLoss, maxLoss));
//        etStopWinDot.setHint(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment54), minWin, maxWin));
        tvStopLoseDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment55)));
        tvStopWinDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment56)));
        btTrade.setBackground(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.level_shape_green : R.drawable.level_shape_green2));
        if (userData != null) {
            btTrade.setText(isBuy ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment57) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment58));
            ClickUtil.click(btTrade, () -> {
                if (checkParam()) {
                    if (isBuy) {
                        if (isMarketPrice) {
                            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
                        } else {
                            orderPrice = etPrice.getText().toString();
                        }
                    } else {
                        if (isMarketPrice) {
                            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
                        } else {
                            orderPrice = etPrice.getText().toString();
                        }
                    }
                    orderPrice = NumberUtil.keepMax(orderPrice, numUSTDKeepDot);
//                    //止损点位
//                    dotLoss = 0;
//                    //止赢点位
//                    dotWin = 0;
//                    if (!TextUtils.isEmpty(etStopWinDot.getText())) {
//                        dotWin = new BigDecimal(orderPrice).add(new BigDecimal("-" + etStopWinDot.getText().toString())).abs().divide(new BigDecimal(minFloatPrice), 0, RoundingMode.HALF_UP).intValue();
//                    }
//                    if (!TextUtils.isEmpty(etStopLoseDot.getText())) {
//                        dotLoss = new BigDecimal(orderPrice).add(new BigDecimal("-" + etStopLoseDot.getText().toString())).abs().divide(new BigDecimal(minFloatPrice), 0, RoundingMode.HALF_UP).intValue();
//                    }
                    TipLevelUtil.showTradeInfo(getActivity(),
                            isBuy ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment57) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment58),
                            isMarketPrice ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment27) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment28),
                            orderPrice,
                            etNum.getText().toString(),
                            NumberUtil.keepMax(etStopWinDot.getText().toString().trim(), 2),
                            NumberUtil.keepMax(etStopLoseDot.getText().toString().trim(), 2),
                            level + "", levels, NumberUtil.keepMax(tvTradeMoney.getText().toString().trim(), 2), fee, () -> {

//                                new BigDecimal(etStopWinDot.getText().toString()).add()
                                mPresenter.createOrder(etNum.getText().toString(),
                                        orderPrice,
                                        code,
                                        isMarketPrice ? "1" : "2",
                                        isBuy ? "2" : "1",
                                        TextUtils.isEmpty(etStopWinDot.getText()) ? "0" : etStopWinDot.getText().toString(),
                                        TextUtils.isEmpty(etStopLoseDot.getText()) ? "0" : etStopLoseDot.getText().toString(),
                                        level + "");
                            });
                }
            });
        } else {
            btTrade.setText(App.INSTANCE.getString(R.string.levelBuyAndSellFragment16));
            ClickUtil.click(btTrade, () -> {
                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
            });
        }
        changeShowData();
    }

    /**
     * 计算最大可输入数量
     */
    private void calculateMaxTrade() {
        if (TextUtils.isEmpty(currentPrice) || Double.valueOf(currentPrice) == 0) {
            maxTradeCoin = "0";
        } else {
            if (isMarketPrice) {
                maxTradeCoin = new BigDecimal(usdtMoney).multiply(new BigDecimal(level)).divide(new BigDecimal("1").add(new BigDecimal(fee)).multiply(new BigDecimal(marketPrice)), 8, BigDecimal.ROUND_HALF_UP).intValue() + "";
            } else {
                maxTradeCoin = new BigDecimal(usdtMoney).multiply(new BigDecimal(level)).divide(new BigDecimal("1").add(new BigDecimal(fee)).multiply(new BigDecimal(currentPrice)), 8, BigDecimal.ROUND_HALF_UP).intValue() + "";
            }
        }
    }

    /**
     * 检测购买条件
     *
     * @return
     */
    private boolean checkParam() {
        if (userData == null) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment35));
            return false;
        }

        if (!AppOuterCheckUtil.checkTel(getActivity(), userData)) {
            return false;
        }
        if (isMarketPrice) {
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment83), isBuy ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment84) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment85)));
                return false;
            }
        } else {
            if (TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment86), isBuy ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment84) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment85)));
                return false;
            }
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment83), isBuy ? App.INSTANCE.getString(R.string.levelBuyAndSellFragment84) : App.INSTANCE.getString(R.string.levelBuyAndSellFragment85)));
                return false;
            }
        }
        if (Double.valueOf(etNum.getText().toString()) < Double.valueOf(minTradeCoin)) {
            ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment92), minTradeCoin));
            return false;
        }
        String stoploss = etStopLoseDot.getText().toString().trim();
        String stopwin = etStopWinDot.getText().toString().trim();
        if (TextUtils.isEmpty(stopwin)) {
            stopwin = "0";
        } else {
            if (new BigDecimal(stopwin).doubleValue() >= new BigDecimal(mathPrice(isBuy, 1)).doubleValue()) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment94) + maxWin);
                ToastUtil.showShort("最大止盈价格小于" + mathPrice(isBuy, 1));
                return false;
            }
            if (new BigDecimal(stopwin).doubleValue() <= new BigDecimal(mathPrice(isBuy, 0)).doubleValue()) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment95) + minWin);
                ToastUtil.showShort("最小止盈价格大于" + mathPrice(isBuy, 0));
                return false;
            }
        }
        if (TextUtils.isEmpty(stoploss)) {
            stoploss = "0";
        } else {
            if (new BigDecimal(stoploss).doubleValue() >= new BigDecimal(mathPrice(isBuy, 3)).doubleValue()) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment97) + maxLoss);
                ToastUtil.showShort("最大止损价格小于" + mathPrice(isBuy, 3));
                return false;
            }
            if (new BigDecimal(stoploss).doubleValue() <= new BigDecimal(mathPrice(isBuy, 2)).doubleValue()) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelBuyAndSellFragment98) + minLoss);
                ToastUtil.showShort("最小止损价格大于" + mathPrice(isBuy, 2));
                return false;
            }
        }
        return true;
    }

    /**
     * 根据
     * 价格，数量，滑竿更新交易额
     * 价格*数量*（1+手续费）/杠杆
     */
    private void changeShowData() {
        if (TextUtils.isEmpty(etPrice.getText())) {
            tvTradeMoney.setText("0 USDT");
//            etStopWinDot.setHint(App.INSTANCE.getString(R.string.levelBuyAndSellFragment100));
//            etStopLoseDot.setHint(App.INSTANCE.getString(R.string.levelBuyAndSellFragment101));
            inputLayoutWin.setHint("");
            inputLayoutLoss.setHint("");
            tvStopWinDot.setText(App.INSTANCE.getString(R.string.levelBuyAndSellFragment100));
            tvStopLoseDot.setText(App.INSTANCE.getString(R.string.levelBuyAndSellFragment101));
        } else {
            String orderPrice = etPrice.getText().toString();
            String usdtFull = "0";
            if (!TextUtils.isEmpty(etNum.getText())) {
                //计算交易额
                if (isBuy) {
                    if (isMarketPrice) {
                        orderPrice = new BigDecimal(currentPrice).add(new BigDecimal(distancePrice)).toPlainString();
                    }
                    usdtFull = new BigDecimal(orderPrice).multiply(new BigDecimal(etNum.getText().toString())).divide(new BigDecimal(level), 8, RoundingMode.HALF_UP).toPlainString();
                } else {
                    if (isMarketPrice) {
                        orderPrice = new BigDecimal(etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
                    }
                    usdtFull = new BigDecimal(orderPrice).multiply(new BigDecimal(etNum.getText().toString())).divide(new BigDecimal(level), 8, RoundingMode.HALF_UP).toPlainString();
                }
//                usdtFull = new BigDecimal(usdtFull).multiply(new BigDecimal("1").add(new BigDecimal(fee))).toPlainString();
                String usdt;
                usdt = NumberUtil.keep(usdtFull, numUSTDKeepDot);
                tvTradeMoney.setText(usdt);
            } else {
                tvTradeMoney.setText("0");

            }
            if (!TextUtils.isEmpty(etStopWinDot.getText())) {
                String input = etStopWinDot.getText().toString();
                stopWinPrice = "0";
                if (isBuy) {
                    orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
                    stopWinPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal(minFloatPrice))).toPlainString();
                } else {
                    orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
                    stopWinPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
                }
                stopWinPrice = NumberUtil.keepMax(stopWinPrice, numUSTDKeepDot);
                tvStopWinDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment46), stopWinPrice));
            }
            if (!TextUtils.isEmpty(etStopLoseDot.getText())) {
                String input = etStopLoseDot.getText().toString();
                stopLossPrice = "0";
                if (isBuy) {
                    orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
                    stopLossPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
                } else {
                    orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
                    stopLossPrice = new BigDecimal(orderPrice).add(new BigDecimal(input).multiply(new BigDecimal(minFloatPrice))).toPlainString();
                }
                stopLossPrice = NumberUtil.keepMax(stopLossPrice, numUSTDKeepDot);
                tvStopLoseDot.setText(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment41), stopLossPrice));
            }

//            //计算止赢止损价格
//            winMinPrice = "0";
//            winMaxPrice = "0";
//            lossMinPrice = "0";
//            lossMaxPrice = "0";
//            if (isBuy) {
//                orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
//                winMinPrice = new BigDecimal(orderPrice).add(new BigDecimal(minWin).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//                winMaxPrice = new BigDecimal(orderPrice).add(new BigDecimal(maxWin).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//                lossMinPrice = new BigDecimal(orderPrice).add(new BigDecimal(maxLoss).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//                lossMaxPrice = new BigDecimal(orderPrice).add(new BigDecimal(minLoss).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//            } else {
//                orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal("-" + distancePrice)).toPlainString();
//                winMinPrice = new BigDecimal(orderPrice).add(new BigDecimal(maxWin).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//                winMaxPrice = new BigDecimal(orderPrice).add(new BigDecimal(minWin).multiply(new BigDecimal("-" + minFloatPrice))).toPlainString();
//                lossMinPrice = new BigDecimal(orderPrice).add(new BigDecimal(minLoss).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//                lossMaxPrice = new BigDecimal(orderPrice).add(new BigDecimal(maxLoss).multiply(new BigDecimal(minFloatPrice))).toPlainString();
//            }
//            winMinPrice = keepMinZore(NumberUtil.keep(winMinPrice, numUSTDKeepDot));
//            winMaxPrice = keepMinZore(NumberUtil.keep(winMaxPrice, numUSTDKeepDot));
//            lossMinPrice = keepMinZore(NumberUtil.keep(lossMinPrice, numUSTDKeepDot));
//            lossMaxPrice = keepMinZore(NumberUtil.keep(lossMaxPrice, numUSTDKeepDot));

            inputLayoutLoss.setHint(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment117), minLoss, maxLoss));
            inputLayoutWin.setHint(String.format(App.INSTANCE.getString(R.string.levelBuyAndSellFragment118), minWin, maxWin));
        }
    }

    public String keepMinZore(String price) {
        if (Double.valueOf(price) <= 0) {
            return "0";
        } else {
            return price;
        }
    }

    public void buySuccess() {
        RxBus.getDefault().send(RxBusCode.LEVEL_FRESH);
    }

    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getRisk());
    }

    public void updateRisk(TradeInfoBean data) {
        if (dymicQy != null && levelFxl != null) {
            try {
                AndroidSchedulers.mainThread().scheduleDirect(() -> {
                    if (dymicQy == null) {
                        return;
                    }
                    if (levelFxl == null) {
                        return;
                    }
                    if (data != null) {
                        dymicQy.setText(data.getAllFound());
                        levelFxl.setText(data.getProportion());
                    } else {
                        dymicQy.setText("--");
                        levelFxl.setText("--");
                    }
                });
            } catch (Exception e) {

            }
        }
    }

    /**
     * K线图选择做多做空
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chooseLevel(MoreLessBean moreLessBean) {
        if (moreLessBean.isMoreLess()) {
            radioGroup.check(R.id.rbBuy);
        } else {
            radioGroup.check(R.id.rbSell);
        }
        isBuy = moreLessBean.isMoreLess();
        isMarketPrice = true;
        code = moreLessBean.getCode();
        type = moreLessBean.getCode().split("/")[0].toUpperCase();
        resetFiveUI();
        mPresenter.getPankou(code);
        refresh();

    }

    /**
     * 根据最小浮动价  当前价格  点位计算
     * 最小止盈价（0） 最大止盈价（1）
     * 最小止损价（2） 最大止损价（3）
     * 做多（true）
     * 做空(false)
     */
    public String mathPrice(boolean isBuy, int type) {
        String mathPrice = "";
        if (isBuy) {  // 做多
            switch (type) {
                case 0:
                    //  最小止盈价 = 当前价格 + （最小波动价 * 最小止盈点位<minStopProfit>）
                    mathPrice = new BigDecimal(marketPrice).add(new BigDecimal(minFloatPrice).multiply(new BigDecimal(minWin))).toPlainString();
                    break;
                case 1:
                    // 最大止盈价 = 当前价格 + （最小波动价 * 最大止盈点位<stopProfit>）
                    mathPrice = new BigDecimal(marketPrice).add(new BigDecimal(minFloatPrice).multiply(new BigDecimal(maxWin))).toPlainString();
                    break;
                case 2:
                    // 最小止损价 = 当前价格 + （最小波动价 * 最小止损点位<minStopLoss>）
                    mathPrice = new BigDecimal(marketPrice).add(new BigDecimal(minFloatPrice).multiply(new BigDecimal(minLoss))).toPlainString();
                    break;
                case 3:
                    // 最大止损价 = 当前价格 + （最小波动价 * 最大止损点位<stopLoss>）
                    mathPrice = new BigDecimal(marketPrice).add(new BigDecimal(minFloatPrice).multiply(new BigDecimal(maxLoss))).toPlainString();
                    break;
            }
        } else {  // 做空
            switch (type) {
                case 0:
                    //  最小止盈价 = 当前价格 -（最小波动价 * 最小止盈点位<minStopProfit>）
                    mathPrice = new BigDecimal(marketPrice).multiply(new BigDecimal(minFloatPrice).multiply(new BigDecimal(minWin))).toPlainString();
                    break;
                case 1:
                    // 最大止盈价 = 当前价格 -（最小波动价 * 最大止盈点位<stopProfit>）
                    mathPrice = new BigDecimal(marketPrice).multiply(new BigDecimal(minFloatPrice).multiply(new BigDecimal(maxWin))).toPlainString();
                    break;
                case 2:
                    // 最小止损价 = 当前价格  -（最小波动价 * 最小止损点位<minStopLoss>）
                    mathPrice = new BigDecimal(marketPrice).multiply(new BigDecimal(minFloatPrice).multiply(new BigDecimal(minLoss))).toPlainString();
                    break;
                case 3:
                    // 最大止损价 = 当前价格 - （最小波动价 * 最大止损点位<stopLoss>）
                    mathPrice = new BigDecimal(marketPrice).multiply(new BigDecimal(minFloatPrice).multiply(new BigDecimal(maxLoss))).toPlainString();
                    break;
            }
        }
        return mathPrice;
    }

}
